//
//  HRCartViewController.m
//  haierapp
//
//  Created by Xia Zhiyong on 14-8-8.
//  Copyright (c) 2014年 haier. All rights reserved.
//

#import "HRCartViewController.h"
#import "HRShoppingCartTableViewCell.h"
#import "HRGoodsInfoViewController.h"
#import "HROrderInfoViewController.h"
#import "HRShopCartModel.h"
#import "HRProductInfo.h"

#import "HRAppDelegate.h"


@interface HRCartViewController (){
    NSMutableArray *arrayTable;
    NSMutableArray *arraySelected;
}

@end

@implementation HRCartViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (__CUR_IOS_VERSION >= __IPHONE_7_0)
    {
        self.edgesForExtendedLayout= UIRectEdgeNone;
    }
    
    
    [_viewFoot removeFromSuperview];
    [_lblTotal setTextAlignment:RTTextAlignmentRight];
    _tableView.tableFooterView = _viewFoot;
    
    arrayTable = [[NSMutableArray alloc] init ];
    arraySelected = [[NSMutableArray alloc] init];
    
}

-(void)viewDidAppear:(BOOL)animated{
    
    HRUser *user=[HRCommonData shareCommonData].curUser;
    
    BOOL isLoad=[HRCommonData shareCommonData].hasNewShopCar;
    
    if (isLoad) {
        
        if (user!=nil) {
            //同步本地缓存数据
            [self SyncShopCarData:^{
                [self loadCartListDataFromServer];
            }];
        }else{
            [self loadCartListDataFromCache];
        }
        
        [HRCommonData shareCommonData].hasNewShopCar=NO;//购物车没有新的产品
    }
    [super viewDidAppear:YES];
}

//同步本地购物车数据与服务器数据
-(void)SyncShopCarData:(void(^)())complete{
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    NSMutableArray *productArray=[defaults objectForKey:SHOP_CAR_DEFAULTS];
    
    NSMutableString *productIds=[NSMutableString string];

    int count=0;
    
    if (productArray!=nil && [productArray count]>0) {
        count=[productArray count];
    }
    //获取产品ID列表
    for (int i=0; i<count; i++) {
        NSDictionary *infoDic=[productArray objectAtIndex:i];
        HRProductInfo *info=[[HRProductInfo alloc]initWithDictionary:infoDic error:nil];
        
        [productIds appendString:info.productId];
        
        if (i<(count-1)) {
            [productIds appendString:@","];
        }
    }
    
    //清空本地缓存
    [[HRCommonData shareCommonData] clearProductsFromShopCar];
    
    if (![productIds isEqualToString:@""]) {
        //添加多个商品到购物车
        [self showCustomLoadingHud:kLoading inView:nil];
        
        [HRInterfaceManager addProductToShopCar:productIds completion:^(BOOL isSucceed, NSString *message, id data) {
            
            [self hideCustomLoadingHud];
            
            if (isSucceed) {
                complete();
            }else{
                [self showTextHUD:message];
                complete();
            }
            
        }];
    }else{
        complete();
    }
    
}

//从服务器上获取购物车数据
-(void)loadCartListDataFromServer{
    
    //隐藏为空提示
    [self hideHud];
    
    _viewBottom.hidden=NO;
    
    [self showCustomLoadingHud:kLoading inView:nil];
    [arrayTable removeAllObjects];
    [HRInterfaceManager getProductListByUid:nil completion:^(BOOL isSucceed, NSString *message, id data) {
        [self hideCustomLoadingHud];
        
        if (isSucceed) {
            HRShopCartModel *listModel = (HRShopCartModel*)data;
            [arrayTable removeAllObjects];
            [arrayTable addObjectsFromArray:listModel.list];
            
            //改变商品数量后，更新已选中商品数量
            NSMutableArray *tempArray = [[NSMutableArray alloc] init];
            for (HRProductInfo *info in arraySelected) {
                for (HRProductInfo *tinfo in arrayTable) {
                    if ([info.productId isEqualToString:tinfo.productId]) {
                        [tempArray addObject:tinfo];
                        break;
                    }
                }
            }
            [arraySelected removeAllObjects];
            [arraySelected addObjectsFromArray:tempArray];
            [self refreshAllPrice];
            
            //判断是否所有商品被选中
            if (arrayTable.count == arraySelected.count) {
                _btnSelectAll.selected = YES;
            }else{
                _btnSelectAll.selected = NO;
            }
            
            [_tableView reloadData];
            [self refreshAllPrice];
            
        }else if([message isEqualToString:NO_WIFI_ERROR_CODE]){
            
            //显示无网络页面
            [self showHudByType:HUDTYPE_NO_WIFI];
            _viewBottom.hidden=YES;
            [HRCommonData shareCommonData].hasNewShopCar=YES;//购物车有新的产品
            return ;
        }else{
            
            [self showTextHUDInWindow:message];
            
            [HRCommonData shareCommonData].hasNewShopCar=YES;//购物车有新的产品
        }
        
        
        
        //判断数据是否为空
        if (arrayTable==nil || [arrayTable count]==0) {
            //显示为空提示
            [self showHudByType:HUDTYPE_SHOPPING_CART];
            _viewBottom.hidden=YES;
        }
    }];
    
    
}


//从缓存中获取购物车数据
-(void)loadCartListDataFromCache{
    //隐藏为空提示
    [self hideHud];
    _viewBottom.hidden=NO;
    
    //用户未登录
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    NSMutableArray *productArray=[defaults objectForKey:SHOP_CAR_DEFAULTS];
    
    [arrayTable removeAllObjects];
    
    //从本地加载缓存购物车数据
    for (NSDictionary *infoDic in productArray) {
        HRProductInfo *info=[[HRProductInfo alloc]initWithDictionary:infoDic error:nil];
        
        [arrayTable addObject:info];
    }
    
    //改变商品数量后，更新已选中商品数量
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    for (HRProductInfo *info in arraySelected) {
        for (HRProductInfo *tinfo in arrayTable) {
            if ([info.productId isEqualToString:tinfo.productId]) {
                [tempArray addObject:tinfo];
                break;
            }
        }
    }
    [arraySelected removeAllObjects];
    [arraySelected addObjectsFromArray:tempArray];
    [self refreshAllPrice];
    
    //判断是否所有商品被选中
    if (arrayTable.count == arraySelected.count) {
        _btnSelectAll.selected = YES;
    }else{
        _btnSelectAll.selected = NO;
    }
    
    [_tableView reloadData];
    [self refreshAllPrice];
    
    //判断数据是否为空
    if (arrayTable==nil || [arrayTable count]==0) {
        //显示为空提示
        [self showHudByType:HUDTYPE_SHOPPING_CART];
        _viewBottom.hidden=YES;
    }
    
}

//刷新已选中的商品价格
-(void)refreshAllPrice{
    CGFloat price = 0.0f;
    for (HRProductInfo *info in arraySelected) {
        price += [info.price floatValue]*[info.goodsAmount integerValue];
    }
    _lblPrice.text = [NSString stringWithFormat:@"<font size=12 color='#ff8730'>合计：</font><font size=15 color='#ff8730'> ¥%.2f </font>",price];
}

-(void)editTable:(id)sender{
    UIBarButtonItem *barItem = (UIBarButtonItem*)sender;
    if ([barItem.title isEqualToString:@"编辑"]) {
        barItem.title = @"完成";
        [_tableView setEditing:YES];
    }else{
        barItem.title = @"编辑";
        [_tableView setEditing:NO];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - TableView

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return arrayTable.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 40;
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *bgV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, 40)];
    bgV.backgroundColor = [UIColor clearColor];
    RTLabel *lbl = [[RTLabel alloc] initWithFrame:CGRectMake(10, 5, bgV.bounds.size.width-20, 30)];
    [lbl setTextAlignment:RTTextAlignmentRight];
    
    int total = 0;
    CGFloat price = 0.0f;
    for (HRProductInfo *info in arrayTable) {
        total += [info.goodsAmount intValue];
        price += [info.price floatValue]*[info.goodsAmount intValue];
    }
    lbl.text = [NSString stringWithFormat:@"<font size=12 color='#666666'>共</font><font size=15 color='#333333'> %d </font><font size=12 color='#666666'>件商品  合计:</font><font  size=15 color='#666666'>¥%.2f</font>",total,price];
    [bgV addSubview:lbl];
    return bgV;
}


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"HRShoppingCartTableViewCell";
    HRShoppingCartTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[HRShoppingCartTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    //cell数量btn点击block
    cell.numChange = ^(int type,NSString* pId){
        
        //判断是否登陆
        HRUser *user=[HRCommonData shareCommonData].curUser;
        
        if (user==nil) {
            //没有登陆，不执行操作
            return ;
        }
        
        if (type == -1) {
            //[self showTextHUD:@"商品数量不能少于1个"];
            return ;
        }
        
        [self showCustomLoadingHud:kLoading inView:nil];
        [HRInterfaceManager editShopCarCount:type productId:pId nowGoodsAmount:1 completion:^(BOOL isSucceed, NSString *message, id data) {
            [self hideCustomLoadingHud];
            
            if (isSucceed) {
                [self loadCartListDataFromServer];
            }else {
                [self showTextHUD:message];
            }
        }];
    };
    //cell选择按钮点击block
    cell.selectOrCancelPrdouct = ^(BOOL isSelect,HRShoppingCartTableViewCell *theCell){
        NSIndexPath *theIndex = [tableView indexPathForCell:theCell];
        HRProductInfo *theInfo = [arrayTable objectAtIndex:theIndex.row];
        if (isSelect) {  //选择商品
            [arraySelected addObject:theInfo];
            //判断是否所有商品都被选中
            if (arraySelected.count == arrayTable.count) {
                _btnSelectAll.selected = YES;
            }
        }else{ //取消商品
            _btnSelectAll.selected = NO;
            [arraySelected removeObject:theInfo];
        }
        [_tableView reloadRowsAtIndexPaths:@[theIndex] withRowAnimation:NO];
        [self refreshAllPrice];
    };
    
    BOOL isSelected = NO;
    if ([arraySelected containsObject:[arrayTable objectAtIndex:indexPath.row]]) {
        isSelected = YES;
    }
    [cell configWithData:[arrayTable objectAtIndex:indexPath.row] isSelected:isSelected];
    return cell;
    
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    HRProductInfo *info = [arrayTable objectAtIndex:indexPath.row];
    
    HRUser *user=[HRCommonData shareCommonData].curUser;
    
    if (user!=nil) {
        //已登录
        
        [HRInterfaceManager deleteAllSc:[NSString stringWithFormat:@"%@",info.productId ] completion:^(BOOL isSucceed, NSString *message, id data) {
            
            if (isSucceed) {
                [self showSuccessHudInWindow:message];
                
                
                [arraySelected removeObject:info];
                [arrayTable removeObjectAtIndex:indexPath.row];
                [_tableView reloadData];
                //判断购物车是否被清空
                if (arrayTable.count == 0) {
                    [self showHudByType:HUDTYPE_SHOPPING_CART];
                }
                
                //刷新总价
                [self refreshAllPrice];
            }else{
                [self showTextHUD:message];
                
            }
        }];
    }else{
        
        
        [[HRCommonData shareCommonData] deleteProductFromShopCar:info.productId];
        
        [self loadCartListDataFromCache];
    }
    
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    HRProductInfo *info = [arrayTable objectAtIndex:indexPath.row];
    HRGoodsInfoViewController *viewC = [[HRGoodsInfoViewController alloc] initWithNibName:@"HRGoodsInfoViewController" bundle:nil];
    viewC.goodsId = info.productId;
    [self.tabBarController.navigationController pushViewController:viewC animated:YES];
}

//全选按钮点击
- (IBAction)actionToSelectAll:(id)sender {
    UIButton *btn = (UIButton*)sender;
    btn.selected = !btn.selected;
    if (btn.selected) {
        [arraySelected removeAllObjects];
        [arraySelected addObjectsFromArray:arrayTable];
    }else{
        [arraySelected removeAllObjects];
    }
    [self refreshAllPrice];
    [_tableView reloadData];
}

//确定按钮点击
- (IBAction)actionSure:(id)sender {
    
    //判断是否登陆
    HRUser *user=[HRCommonData shareCommonData].curUser;
    if (user==nil) {
        [kAppDelegate showUserLoginCompletion:nil];
        return;
    }
    
    if (arraySelected.count == 0) {
        [self showTextHUD:@"请选择商品"];
        return;
    }
    
    //购物车逻辑验证
    BOOL isPass=[self isPassByShopCarLimit];
    
    if (!isPass) {
        return;
    }

  
    HROrderInfoViewController *viewC = [[HROrderInfoViewController alloc] initWithNibName:NIBNAME_ORDER_INFO bundle:nil];
    viewC.arrayGoods = arraySelected ;
    viewC.activityType=ACTIVITY_TYPE_NORMAL;//普通商品
    viewC.type=ORDER_CONFIRM_TYPE_SHOPCAR;//从购物车生成订单
    
    [self.tabBarController.navigationController pushViewController:viewC animated:YES];
}

//购物车逻辑限制
-(BOOL)isPassByShopCarLimit{
    
    BOOL DXFlag=FALSE;
    int isDX;//0:大件 1:小件
    
    if ([arraySelected count]>0) {
        HRProductInfo *info=[arraySelected objectAtIndex:0];
        isDX=[info.isDX intValue];
        
    }
    
    CGFloat price = 0.0f;
    for (HRProductInfo *info in arraySelected) {
        price += [info.price integerValue]*[info.goodsAmount integerValue];
        
        if ([info.isDX intValue]!=isDX) {
            DXFlag=TRUE;//一个订单存在大小件商品
        }
        
    }
    
    //订单金额不能大于10W
    if (price>100000) {
        [self showTextHUD:@"订单金额不能超过10万"];
        return NO;
    }

    //大小件商品不能同时下单
    if (DXFlag) {
        [self showTextHUD:@"大小件商品不能同时下单"];
        return NO;
    }
   
    return YES;
}


#pragma mark - HRProgress Delegate Methods
//到处逛逛/重新加载
-(void)tapHUDButtonAction:(id)button{
    
    UIButton *theButton=(UIButton *)button;
    
    if ([theButton.titleLabel.text isEqualToString:@"重新加载"]) {
        //重新加载
        HRUser *user = [HRCommonData shareCommonData].curUser;
        
        if (user==nil) {
            //未登录
            [self loadCartListDataFromCache];
        }else{
            [self loadCartListDataFromServer];
        }
        
    }else{
        //去逛逛
        [self.navigationController.tabBarController setSelectedIndex:0];
    }
    
}

@end
